#include "common.h"
#include <termios.h>

int uart_fd = 0;
uint8 uart_buf[PZ_PL_UART_DLEN] = { 0 };

int set_uart_options(int baud, int fd)
{
    int ret;
    struct termios options;

    ret = tcgetattr(fd, &options);
    if (-1 == ret)
        return -1;


    options.c_cflag &= ~CSIZE;    //屏蔽其他标志
    options.c_cflag |= CS8;        //将数据位修改为8bit
    options.c_cflag |= (PARODD|PARENB);
    options.c_cflag &= ~CSTOPB; // 设置一位停止位;


    options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
    cfsetispeed(&options, baud);
    cfsetospeed(&options, baud);
    options.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
    options.c_cc[VTIME] = 1; //时间
	options.c_cc[VMIN] = 0;
    ret = tcsetattr(fd, TCSANOW, &options);
    if (-1 == ret)
        return -1;
    return fd;
}

void Uart422_init() {
    struct termios options;
    uart_fd = open(PZ_PL_UART_422, O_RDWR | O_NOCTTY);     /* 读写权限，非阻塞 */
    set_uart_options(B19200, uart_fd);
    if(uart_fd < 0) {
        LOG_ERROR("Uart 422 init error, errmsg: %s", strerror(errno));
        return ;
    } 
    LOG_INFO("Uart 422 init successful");
}

int Uart_send(uint8 *rbuf, int len) {
    if(len !=  write(uart_fd, rbuf, len)) {
        LOG_ERROR("Err to send uart data, err: %s", strerror(errno));
        return KT_ERROR;
    }
    // LOG_DEBUG("uart 422 send data successful, dlen : %d", len);
    return KT_OK;
}

int Uart_recv(int len, int timeouts) {
    memset(uart_buf, 0x0, sizeof(uart_buf));
    int cnt = 0;
    int res = 0;
    uint8 buf[1];
    int timeout = 0;
    while(1) {
        int res = read(uart_fd, buf, sizeof(buf));
        if(res != 0) {
            timeout = 0;
            uart_buf[cnt] = buf[0];
            cnt ++;
            // printf("rlen =>%d %d %02x\n", cnt, res, buf[0]);
        } else {
            timeout++;
        }

        if(cnt >= PZ_PL_UART_DLEN) {
            break;
        }

        if(timeout > timeouts) {
            LOG_INFO("uart recv timeout");
            break;
        }
    }
    return PZ_PL_UART_DLEN;
}